package com.jblv.frame.common.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title ProjectPathUtils
 * @projectName jblv-frame
 * @packageName com.jblv.common.utils
 * @description ProjectPathUtils
 * @date Create at 2020/5/7 10:47
 * @since jdk1.8
 */


public class ProjectPathUtils {
    public static final String CONFIG_FOLDER = "config";

    public ProjectPathUtils() {
    }

    public static String getRunTimePath() {
        return System.getProperty("user.dir");
    }

    public static String getClassesPath() {
        URL path = Thread.currentThread().getContextClassLoader().getResource("");
        return path.getPath();
    }

    public static String getConfigPath(boolean isJarRun) {
        return isJarRun ? getRunTimePath() + File.separator + "config" : getClassesPath() + File.separator + "config";
    }

    public static String getPath(String fileName) {
        String filePath = System.getProperty("user.dir") + File.separator + fileName;
        if ((new File(filePath)).exists()) {
            return filePath;
        } else {
            URL url = ProjectPathUtils.class.getClassLoader().getResource(fileName);
            return url != null && (new File(url.getPath())).exists() ? url.getPath() : null;
        }
    }

    public static String getPath(String fileName, String encoding) {
        String filePath = System.getProperty("user.dir") + File.separator + fileName;
        if ((new File(filePath)).exists()) {
            return filePath;
        } else {
            URL url = ProjectPathUtils.class.getClassLoader().getResource(fileName);
            if (url == null) {
                return null;
            } else {
                try {
                    filePath = URLDecoder.decode(url.getPath(), encoding);
                } catch (UnsupportedEncodingException var5) {
                    var5.printStackTrace();
                }

                return (new File(filePath)).exists() ? filePath : null;
            }
        }
    }
}
